<?php

/**
 *   OPENSHOP_taobao 商品相关设置
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: api_tb_app.php,v 1.0 2009/11/5 07:35:58 add $
 *   @author      winner <jsycywm@hotmail.com>
 */

define('IN_OS', true);

require_once(dirname(__FILE__).'/includes/init.php'); 
require(ROOT_PATH . '/includes/modules/taobao.api/cls_api.php');
$exc = new exchange($os->table('tb_app'),$db,'id','app_key');
	
/* act操作项的初始化 */
if (empty($_REQUEST['act'])){
    $_REQUEST['act'] = 'list';
}else{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}


if($_REQUEST['act']=='list')
{	
	if($_REQUEST['status']=='' ) { 
		$sql="  update open_tb_app set is_use=0  ";
		$db->query($sql); 
		$sql="update open_tb_app,open_shop_config set is_use=1 where code='taobao_app_key' and value=app_key"; 
		$db->query($sql); 
		$stuats = $db->getOne("select app_key from open_tb_app where is_use=1");//   
	}else { 
		$stuats=$_REQUEST['status']; //app_key
		$sql="update open_shop_config,open_tb_app set value=nick   where code='taobao_user' and app_key=".$stuats ;
		$db->query($sql); 
		$sql="  update open_shop_config,open_tb_app set value=app_secret   where code='taobao_app_secret' and app_key=".$stuats ;
		$db->query($sql); 
		$sql="  update open_shop_config,open_tb_app set value=app_key   where code='taobao_app_key' and app_key=".$stuats ;
		$db->query($sql); 
		$sql="  update open_shop_config,open_tb_app set value =ifnull(app_session,'')   where code='taobao_sessionkey' and app_key=".$stuats ;
		$db->query($sql); 
		$sql="  update open_tb_app set is_use=0  ";
		$db->query($sql); 
		$sql="  update open_tb_app set is_use=1  where app_key=".$stuats ;
		$db->query($sql); 
		clear_cache_files();  /* 清除缓存 */ 
	}    
	$smarty->assign('ur_here',      '淘宝应用管理');    
	$smarty->assign('action_link',  array('href' => 'api_tb_app.php?act=add', 'text' => '添加应用'));
	$app_list = get_tb_app_list();   
	$data_format_app = $db->getAll('select *  from open_tb_app') ;   
	$smarty->assign('select_app',    $stuats );  
	$smarty->assign('data_format_app',    $data_format_app ); 
	$smarty->assign('app_list',   $app_list['app']);
    $smarty->assign('filter',       $app_list['filter']);
    $smarty->assign('record_count', $app_list['record_count']);
    $smarty->assign('page_count',   $app_list['page_count']);		 
	$smarty->assign('full_page',    1); 
    assign_query_info();    
	$smarty->display('api_tb_app_list.tpl');	
} elseif ($_REQUEST['act'] == 'getsession'){  
//		LoginTaoBao("优衣派服饰专营店" ,"xin894774212wu" );  
	    include_once(ROOT_PATH . '/includes/modules/taobao.api/Snoopy.class.php');
		$snoopy = new Snoopy; 
		$appkey = $_REQUEST['appkey']; 
		$formurl = 'http://open.taobao.com/authorize/?appkey=' . $appkey;
		$formvars = array(); 
		$formvars['protocol'] = 'agree'; 
		$snoopy -> submit($formurl,$formvars);
//		echo $snoopy -> results;
//		$res = preg_match_all("/value=.*style=/",htmlentities($snoopy -> results),$matches);
//		$authcode = $matches[0][0];
//		$authcode = substr($authcode, 12);
//		$authcode = substr($authcode, 0, -13);
		echo "<a href=".$formurl.">authcode===>". $formurl."</a><br/>";
		echo " 获取SessionKey的容器地址：http://container.open.taobao.com/container?authcode={授权码} ";
		
		 
}elseif($_REQUEST['act']=='add'){ 
	/* 权限检查 */ 
    $smarty->assign('ur_here',      '添加应用');   
	$smarty->assign('action_link',  array('href' => 'api_tb_app.php?act=list', 'text' => '应用管理'));
	$smarty->assign('form_action',     'insert'); 
	assign_query_info();	
	$smarty->display('api_tb_app_info.tpl');	
}elseif($_REQUEST['act']=='insert'){  
	$is_only = $exc->is_only('app_key', $_POST['app_key']); 
    if (!$is_only) { 
        sys_msg(sprintf('app_key %s 已经存在！', stripslashes($_POST['app_key'])), 1);
    }    
    /*插入数据*/ 
    $bstr = '{$goods_name}';
    $sql = "INSERT INTO ".$os->table('tb_app')."(app_key, app_secret,app_session,app_name,shop_name,nick,password,is_use,bbnamestr) ".
           "VALUES ('$_POST[app_key]','$_POST[app_secret]', '$_POST[app_session]', 
           '$_POST[app_name]', '$_POST[nick]', '$_POST[nick]', '$_POST[password]', '0', '$bstr')";
    $db->query($sql); 
    admin_log($_POST['app_key'],'add','tb_app'); 
    /* 清除缓存 */
    clear_cache_files(); 
    $link[0]['text'] = '继续添加应用';
    $link[0]['href'] = 'api_tb_app.php?act=add'; 
    $link[1]['text'] = '返回应用列表';
    $link[1]['href'] = 'api_tb_app.php?act=list'; 
    sys_msg('应用添加成功！', 0, $link);   
}elseif($_REQUEST['act']=='drop'){ 
	 $app_id =  $_REQUEST['appkey'] ;  
	/* 删除应用 */
	if(  ($db->query("DELETE FROM open_tb_app WHERE app_key='".$app_id."'" ))   )admin_log($app_id, 'remove', 'app'); 
	$url = 'api_tb_app.php?act=list';
	os_header("Location: $url\n");
	exit;
}elseif ($_REQUEST['act'] == 'updatesession'){ 
		$appkey = $_REQUEST['appkey'];
		$sesionkey = $_REQUEST['newsession']; 
		$onsell_min_num = $_REQUEST['onsell_min_num']; 
		$onsell_rate_num = $_REQUEST['onsell_rate_num'];  
		$bbnamestr = $_REQUEST['bbnamestr'];  		
		$sql=" update open_tb_app set app_session='".$sesionkey."',onsell_min_num='".$onsell_min_num."',onsell_rate_num='".$onsell_rate_num."',bbnamestr='".$bbnamestr."' where app_key=".$appkey ;
		$db->query($sql);  
	    echo ($appkey.'应用更新成功! <a href="#" onclick="history.go(-1)">返回</a>');  
}  elseif ($_REQUEST['act'] == 'query'){ 
    $app_list = get_tb_app_list(); 
    $smarty->assign('app_list',   $app_list['app']);
    $smarty->assign('filter',       $app_list['filter']);
    $smarty->assign('record_count', $app_list['record_count']);
    $smarty->assign('page_count',   $app_list['page_count']); 
    make_json_result($smarty->fetch('api_tb_items_list.tpl'), '',
     array('filter' => $app_list['filter'], 'page_count' => $app_list['page_count']));
}elseif($_REQUEST['act']=='relevancy'){    
	$smarty->assign('action_link',  array('href' => 'api_tb_items.php?act=list', 'text' => '淘宝宝贝关联管理'));  
	$num_iid = $_GET['num_iid']   ;     
	$tb_item_name = $db->getOne("select title from open_tb_item where num_iid='".$num_iid."'");   
	$smarty->assign('cat_app_list',get_tb_cat_app_list( $num_iid ));
	$smarty->assign('num_iid',$num_iid);  
	$smarty->assign('vname','['.$num_iid.']'.$tb_item_name);  
   $smarty->assign('ur_here',      '淘宝宝贝('.'['.$num_iid.']'.$tb_item_name.')关联设置' ); 
	assign_query_info();
	$smarty->display('api_tb_app_relevancy.tpl');	
} 
elseif($_REQUEST['act']=='search_cat'){   //查找关联的 
    include_once(ROOT_PATH . 'includes/cls_json.php'); 
    $json   = new JSON;
    $filter = $json->decode($_GET['JSON']);
    $filter->keyword = json_str_iconv($filter->keyword); 
    $sql = "SELECT goods_sn AS id, CONCAT('[',goods_sn,']', goods_name) as name FROM " . $os->table('goods') .
        " WHERE goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' or goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' LIMIT 50";
    
   $arr = $db->getAll($sql);
    if (empty($arr)){
        $arr = array(0 => array(
            'id'   => 0,
            'name' => '没有找到相应记录，请重新搜索'
        ));
    }

    make_json_result($arr);	
    
}elseif ($_REQUEST['act']=='add_cat_item'){ 
    include_once(ROOT_PATH . 'includes/cls_json.php');    
    $json = new JSON; 
    $goods_sn =$json->decode(  $_GET['add_ids'] );
    $goods_sn =$goods_sn[0] ; 
    $arguments  = $json->decode($_GET['JSON']);
    $num_iid   = $arguments[0]; 
	$sql = "update " . $os->table('tb_item') . " set outer_id='".$goods_sn."'where num_iid=". $num_iid; 
	$db->query($sql);  
    $arr = get_tb_cat_goods_list($num_iid );  
    $opt = array(); 
    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['goods_sn'],
                        'text'      => '['.$val['goods_sn'].']'.$val['goods_name'],
                        'data'      => '');
    } 
    clear_cache_files(); 
    make_json_result($opt);
    
}elseif($_REQUEST['act']=='drop_cat_item'){  
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON; 
	$goods_sn =$json->decode(  $_GET['add_ids'] );
	$goods_sn =$goods_sn[0] ; 
	$arguments  = $json->decode($_GET['JSON']);
	$num_iid   = $arguments[0]; 
	$sql = "update " . $os->table('tb_item') . " set outer_id='' where num_iid=". $num_iid;  
    $db->query($sql); 
    $arr = get_tb_cat_goods_list($num_iid);
    $opt = array(); 
    foreach ($arr AS $val){
        $opt[] = array('value'      => $val['cat_id'],
                        'text'      => $val['cat_name'],
                        'data'      => '');
    }
    
    clear_cache_files();
    make_json_result($opt);	
}

function get_tb_app_list(){
	global $_CFG;
    $result = get_filter();
    if ($result === false)
    {
        /* 分页大小 */
        $filter = array();

        $filter['keyword']  = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);

        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }        
        
        if ($filter['keyword'])
        {
			$where .= " AND (tb_app.app_key LIKE '%" . mysql_like_quote($filter['keyword']) . "%' 
						OR tb_app.app_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
						OR tb_app.shop_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
				        OR tb_app.nick LIKE '%" . mysql_like_quote($filter['keyword']) . "%'
						)";
        }     
                
        /* 记录总数以及页数 */
        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['os']->table('tb_app').' as tb_app  
        		where 1 '.$where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql); 
        $filter = page_and_size($filter);

         /* 查询记录 */ 
		$sql = "select *
				from open_tb_app as tb_app where 1 ".$where." ORDER BY  tb_app.id DESC";  
        /* 查询记录 */ 
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    } 
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);
    
    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {   
        $arr[] = $rows;
    }	
    return array('app' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}
 


function get_tb_cat_app_list($num_iid=0){ 
	static $rows = NULL;  
    $sql ="select * from open_tb_app as tb_app "; 
	if($num_iid>0){
		$sql .= " WHERE tb_app.id = '$num_iid'";
	}
	$sql .= " ORDER BY tb_app.id DESC";   
	if ($rows === NULL){
		$rows = $GLOBALS['db']->getAll($sql);
	}
	return $rows;		
}
?>